#include "stdafx.h"
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <stdio.h>

#define MEMORY 2000

int MainMenu();
char* Create_textFile();
void Print_Edit(char *filename_path);
char Set_Sepatator_char();

int main( void )
{
	int choise;
	choise = MainMenu();
	switch (choise)
	{
	case 1: 
		Print_Edit(Create_textFile());
		break;
	case 2:
		printf("Please enter file name or file PATH.\n");
		char file_name[_MAX_PATH];
		char *pt_name;
		pt_name = file_name;
		fflush(stdout);
		fflush(stdin);
		fgets(file_name, (_MAX_PATH - 1), stdin);
		for (int i = 0; i < strlen(file_name); i++)
		{
			if ((file_name[i] == '.') && (file_name[i+1] == 't') && (file_name[i+2] == 'x') &&(file_name[i+3] == 't'))
			{
				file_name[i+4] = '\0';
			}
		}
		Print_Edit(file_name);
		break;
	default :
		printf("Wrong input Menu!");
		break;
	}
	system("PAUSE");
	return 0;
}

void Print_Edit(char *filename_path)
{
   
	FILE *stream;
	char *buffer;
	int  j,ch,sh;
	buffer = (char*)malloc(MEMORY);
	memset(buffer,0,MEMORY);
	sh = Set_Sepatator_char(); 
	j = 1;
	// Open file to read line from:
	fopen_s(&stream,filename_path,"a");
	if (!stream)
	{
		printf("File: %s cannot be opened",filename_path);
		exit(0);
	}
	printf("Loading .....\n");
	printf("Please input your text here:.....\n.Press Ctrl+Z for editing\n");
	fflush(stdin);
	while ((ch = getchar()) != EOF)
	{
		fputc(ch,stream);
	}
	fclose(stream);
	fopen_s(&stream, filename_path, "rt" );
	if( stream == 0 )
	{
		printf("Cannot open file: %s",filename_path);
		system("PAUSE");
		exit( 0 );
	}
	printf("%d.",j);
	// Read text and print on console": 
	while(( feof( stream ) == 0 ))
	{
		ch = fgetc( stream );
		if (ch != sh)
		{
			putc(ch,stdout);
		}
		else 
		{
			putc(ch,stdout);
			printf("\n%d.",++j);
		}
   }
   fclose( stream );
   free(buffer);
}

char Set_Sepatator_char()
{
	printf("Please set symbol separator.\n");
	fflush(stdin);
	char separator = getchar();
	return separator;
}

char* Create_textFile()
{
	FILE *stream;
	char *file_name = "tmp987654321.txt";
	char *pt_fileName = file_name;
	int ch = 0;
	/*fopen_s(&stream,file_name,"w");
	if (!stream)
	{
		printf("File: %s cannot be opened",file_name);
		exit(0);
	}
	printf("Loading .....\n");
	printf("Please input your text here:.....\n.Press Ctrl+Z for editing\n");
	fflush(stdin);
	while ((ch = getchar()) != EOF)
	{
		fputc(ch,stream);
	}
	fclose(stream);*/
	return pt_fileName;
}

int MainMenu()
{
	int choise = 0;
	printf("Welcome to TypeWritter 1.1 ver.\n");
	printf("MENU\n");
	printf("1.Write text.\n");
	printf("2.Open file.\n");
	scanf_s("%d", &choise);
	if ((iswdigit(choise)) || (choise > 0) || (choise < 3))
	{
		return choise;
	}
	else
	{
		printf("Wrong input ..");
		return 0;
	}
}